package org.example;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Service
public class KnowledgeBaseService {
    private final Map<String, String> knowledgeBase = new HashMap<>();

    @Value("classpath:knowledge-base.properties")
    private Resource knowledgeBaseResource;

    @PostConstruct
    public void init() {
        loadKnowledgeBase();
    }

    private void loadKnowledgeBase() {
        try (InputStream inputStream = knowledgeBaseResource.getInputStream()) {
            Properties properties = new Properties();
            // 使用UTF-8编码读取properties文件
            properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            
            for (String key : properties.stringPropertyNames()) {
                knowledgeBase.put(key, properties.getProperty(key));
            }
        } catch (IOException e) {
            // 改为日志记录而不是抛出异常
            System.err.println("警告: 加载知识库配置文件失败，将使用空知识库");
            e.printStackTrace();
        }
    }

    public String queryKnowledgeBase(String question) {
        for (Map.Entry<String, String> entry : knowledgeBase.entrySet()) {
            if (question.contains(entry.getKey())) {
                return entry.getValue();
            }
        }
        return null;
    }

    public void addKnowledge(String key, String answer) {
        knowledgeBase.put(key, answer);
    }
}